package cn.com.jrr.core.service.power;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import cn.com.jrr.core.dao.impl.BaseDaoImpl;
import cn.com.jrr.core.model.power.SysResource;
import cn.com.jrr.core.model.power.SysRole;

@Service
public class SysResourceService {
	@Resource
	private BaseDaoImpl<SysResource> baseDaoImpl;

	public List<SysResource> getResource(Integer id){
		String sql="SELECT * FROM sysresource WHERE resourceParent=?";
		List<SysResource> sysResources=baseDaoImpl.findBySql(sql,SysResource.class, id);
		return sysResources;
	}
	public SysResource get(Integer id){
		return baseDaoImpl.get(SysResource.class, id);
	}
	public boolean hasChildren(Integer id){
		String sql="SELECT COUNT(*) FROM sysresource WHERE resourceParent=?";
		List<Object> list=baseDaoImpl.findBySql(sql,id);
		if(list.size()>0){
			if(Integer.parseInt(list.get(0).toString())>0){
				return true;
			}
		}
		return false;
	}
	/**
	 * 添加数据
	 * */
	public void add(SysResource sysResource){
		baseDaoImpl.save(sysResource);
	}
	/**
	 * 修改数据
	 * */
	public void update(SysResource sysResource){
		baseDaoImpl.update(sysResource);
	}
	/**
	 * 修改数据
	 * */
	public void delete(SysResource sysResource){
		baseDaoImpl.update(sysResource);
	}

	public int delete(Integer id){
		deleteChildrens(id);
		return  baseDaoImpl.updateBySql("delete from sysresource where resourceId=?", new Object[]{id});
	}
	//递归删除子节点
	private void deleteChildrens(Integer id){
		List<Object> objs=baseDaoImpl.findBySql("SELECT DISTINCT resourceId FROM sysresource WHERE resourceParent = ?", new Object[]{id});
		List<Integer> data=new ArrayList<Integer>();
		for(int i=0;i<objs.size();i++){
			Integer rId=(Integer)(objs.get(i));
			data.add(rId);
		}
		if(data.size()>0){
			for(Integer dd:data){
				deleteChildrens(dd);
				baseDaoImpl.updateBySql("delete from sysresource where resourceId=?", new Object[]{dd});
			}
		}
	}

	public List<Object> getResource(String permit){
		String sql="SELECT resourceId FROM sysresource WHERE permit=?";
		List<Object> ids=baseDaoImpl.findBySql(sql, permit);
		return ids;
	}

	//查询菜单
	public List<SysResource> getMenu(Integer userId){
		String sql="SELECT * FROM sysresource WHERE resourceId IN(SELECT resourceId FROM sysroleresource WHERE roleId IN(SELECT roleId FROM sysuserrole WHERE userId=?)GROUP BY resourceId)";
		List<SysResource> data= baseDaoImpl.findBySql(sql, SysResource.class, userId);
		return data;
	}
}
